
import axios from 'axios';
import { Message, Loading } from 'element-ui';
const axiosContext = axios.create({
    timeout: 20000,
    baseURL: '',
    headers: {},
})
export function serviceRequest(params, autoHandleError = true, showLoading = false) {

    // 处理参数
    let dealParams;
    if ('string' === typeof params) {
        dealParams = {
            url: params,
        };
    } else {
        dealParams = {
            ...params,
        };
    }
    if(!dealParams.headers) dealParams.headers = {};
    // dealParams.headers['Cache-Control'] = 'max-age=0';
    const token = sessionStorage.getItem('token');
    dealParams.headers['token'] = token;

    // 默认为get请求
    dealParams.method = dealParams.method || 'get';

    // 如果是get，那么将参数data变成params;
    if ('get' === dealParams.method) {
        dealParams.params = dealParams.data;
    }
    let loadingCtx;
    if (showLoading) {
        loadingCtx = Loading.service({ fullscreen: true });
    }

    return axiosContext.request(dealParams).then((res) => {
        if (showLoading) loadingCtx.close();
        if (0 === res.data.status) {
            return Promise.resolve(res.data);
        } else {
            return Promise.reject(res.data);
        }
    }).catch((err)=> {
        if (loadingCtx) loadingCtx.close();
        if (autoHandleError) {
            if (!!err && !!(err.message || err.content)) {
                Message({
                    showClose: true,
                    message: err.message || err.content,
                    type: 'error',
                });
            } else {
                Message({
                    showClose: true,
                    message: '网络错误,请稍后重试!',
                    type: 'error',
                });
            }

        }
        // 如果不自动处理错误，那么需要手动catch
        return Promise.reject(err);
    });
}
export function login(params) {
    return serviceRequest(params)
}
export function reg(params) {
    return serviceRequest(params);
}
export function getUser(params) {
    return serviceRequest(params);
}
export function resetPassword(params) {
    return serviceRequest(params);
}

export function delUser(params) {
    return serviceRequest(params);
}


export function delCategory(params) {
    return serviceRequest(params);
}
export function getCategory(params) {
    return serviceRequest(params);
}
export function addCategory(params) {
    return serviceRequest(params);
}

// 获取产品
export function getProduct(params) {
    return serviceRequest(params);
}
export function addProduct(params) {
    return serviceRequest(params);
}
export function delProduct(params) {
    return serviceRequest(params);
}